package com.itfreer.power.dao.jurisdiction;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import org.springframework.beans.BeanUtils;

import com.itfreer.form.api.JdbcBaseEntity;
import com.itfreer.power.dao.base.JdbcTreeEntityBase;
import com.itfreer.power.entity.jurisdiction.DataJurisdictionEntity;
import com.itfreer.power.entity.jurisdiction.DataJurisdictionItemEntity;

/**
 * 数据服务
 */
@Entity(name = "sso_jurisdiction_data")
@Table(indexes = { @Index(name = "s_j_d_code", columnList = "s_code"),
		@Index(name = "s_j_d__pid", columnList = "pid") })
public class JdbcDataJurisdictionEntity extends JdbcTreeEntityBase implements JdbcBaseEntity<DataJurisdictionEntity> {

	private static final long serialVersionUID = 13859908252309344L;

	/**
	 * 所属注册的服务
	 */
	@Column(name = "s_registerService", nullable = true)
	private String registerService;

	/**
	 * 子表对象
	 */
	@SuppressWarnings("deprecation")
	@org.hibernate.annotations.ForeignKey(name = "none")
	@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
	@JoinColumn(name = "s_funid")
	@OrderBy("id ASC")
	private Set<JdbcDataJurisdictionItemEntity> items = new HashSet<JdbcDataJurisdictionItemEntity>();

	/**
	 * 所属注册的服务
	 */
	public String getRegisterService() {
		return registerService;
	}

	/**
	 * 所属注册的服务
	 */
	public void setRegisterService(String registerService) {
		this.registerService = registerService;
	}

	/**
	 * 子表对象
	 * 
	 * @return
	 */
	public Set<JdbcDataJurisdictionItemEntity> getItems() {
		return items;
	}

	/**
	 * 子表对象
	 * 
	 * @return
	 */
	public void setItems(Set<JdbcDataJurisdictionItemEntity> items) {
		this.items = items;
	}

	@Override
	public void from(DataJurisdictionEntity entity) {
		BeanUtils.copyProperties(entity, this, "items");
		
		Set<JdbcDataJurisdictionItemEntity> items = new HashSet<JdbcDataJurisdictionItemEntity>();
		Set<DataJurisdictionItemEntity> entityItems = entity.getItems();
		if (entityItems != null) {
			for (DataJurisdictionItemEntity item : entityItems) {
				JdbcDataJurisdictionItemEntity jItem = new JdbcDataJurisdictionItemEntity();
				jItem.from(item);
				items.add(jItem);
			}
		}
		this.setItems(items);
	}

	@Override
	public DataJurisdictionEntity toEntity() {
		DataJurisdictionEntity toEntity = new DataJurisdictionEntity();
		BeanUtils.copyProperties(this, toEntity, "items");
		
		Set<DataJurisdictionItemEntity> items = new HashSet<DataJurisdictionItemEntity>();
		Set<JdbcDataJurisdictionItemEntity> entityItems = this.getItems();
		if (entityItems != null) {
			for (JdbcDataJurisdictionItemEntity item : entityItems) {
				items.add(item.toEntity());
			}
		}
		toEntity.setItems(items);

		return toEntity;
	}
}
